package com.hqyj.realm;

import com.hqyj.dao.UserMapper;
import com.hqyj.pojo.User;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;


public class MyRealm extends AuthorizingRealm {
    //注入mapper
    @Autowired
    UserMapper mapper;

    //授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        //1 获取用户名
        String userName = principals.fromRealm(this.getName()).iterator().next()+"";
        //根据用户名查询角色参数
        List<String> list = mapper.queryRoleParamByUserName(userName);
        //3 把角色的角色参数添加到授权对象中
        SimpleAuthorizationInfo simple = new SimpleAuthorizationInfo();
        //添加角色
        simple.addRoles(list);
        //添加权限
        for (String s:list){
            System.out.println("给用户" + userName + "分配了角色" +s);
        }
        return simple;
    }
    //认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        //1 取出令牌对象
        UsernamePasswordToken t = (UsernamePasswordToken) token;
        //2 取出用户身份
        String userName = t.getPrincipal()+ "";
        //3 查询用户是否存在
        User user = mapper.queryByUserName(userName);
        if (user == null){
            throw new UnknownAccountException();
        }
        //4 创建用户凭证
        //new SimpleAuthenticationInfo(数据查询的用户名，数据查询的加密后密码,算法对象以及盐值,realm名称)
        AuthenticationInfo au = new SimpleAuthenticationInfo(user.getUserName(),user.getUserPwd(),new Md5Hash(user.getSalt()),this.getName());
        return au;

    }
}
